package com.baijiaoxi.common.utils.jdk;

import lombok.Data;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by shixj on 2018/5/15.
 */
@Data
public class SocketUtil {
    private String host;
    private int port;
    private String sendCharset = "utf8";
    private String receiveCharset = "gbk";

    public SocketUtil() {
    }

    public SocketUtil(String host, int port) {
        this.host = host;
        this.port = port;
    }
    public String send(String data) throws Exception {
        Socket socket;
        //对服务端发起连接请求
        socket = new Socket(host, port);
        //给服务端发送响应信息
        OutputStream os = socket.getOutputStream();
        os.write(data.getBytes(sendCharset));
        //接受服务端消息并打印
        InputStream is = socket.getInputStream();
        byte b[] = new byte[1024];
        is.read(b);
        return new String(b, receiveCharset);
    }
}
